package com.eslserver.servletapi.timer;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Map;
import java.util.Properties;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.eslserver.servletapi.core.ESLServletAPIConfig;
import com.eslserver.servletapi.core.ESLServletAPICore;

public class STiTEQCommandTimerInitializer {
	static final Logger LOG = LoggerFactory
			.getLogger(STiTEQCommandTimerInitializer.class);

	public static void initTasksTimer() {
		NodeList elems = ESLServletAPICore.getESLServletAPIConfig().getDoc()
				.getElementsByTagName(ESLServletAPIConfig.CONFIG);
		TimerConfig timerConfig = new TimerConfig();
		try {
			timerConfig.readTimerFromXML((Element) elems.item(0));

			StdSchedulerFactory schedFact = new StdSchedulerFactory();
			schedFact.initialize("eslapiserver.properties");
			Scheduler sched = schedFact.getScheduler();
			sched.start();

			for (Map.Entry<String, Properties> entry : timerConfig.timer
					.entrySet()) {
				Properties prop = entry.getValue();
				String interval = prop.getProperty(TimerConfig.TIMER_INTERVAL);

				if (interval != null && Integer.valueOf(interval) > 0) {
					JobDetail job = newJob(CommandRetryJob.class).build();

					Trigger trigger = newTrigger()
							.startNow()
							.withSchedule(
									simpleSchedule()
											.withIntervalInMilliseconds(
													Integer.valueOf(interval))
											.repeatForever()
											.withMisfireHandlingInstructionNowWithExistingCount())
							.build();

					sched.scheduleJob(job, trigger);
				}
			}
		} catch (Exception e) {
			LOG.error("Timer initialization failed", e);
		}
	}
}
